package com.bugull.farm.core.utils;


import java.util.Date;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;

import com.bugull.farm.core.server.FarmServer;

/**
 * 
 * @author songw
 *
 */
public class GetIPInfoTask extends FutureTask<Boolean>{
	//record some obstinate tasks 
	private static final Map<String, Long> failedTasks = new ConcurrentHashMap<String, Long>();
	
	private final int IGNORE_TIME_MILLISECOND = 5*1000;
	
	private Callable<Boolean> callable;
	private String mac;
	private String ip;	
	
	public GetIPInfoTask(Callable<Boolean> callable) {
		super(callable);
		this.callable = callable;
		this.mac = ((GetIPInfoCallable)callable).getMac();
		this.ip = ((GetIPInfoCallable)callable).getIp();
	}
	
	@Override
	protected void done(){
		if(!((GetIPInfoCallable)callable).isSuccess()){
			//query the task in the failedList
			if(getFailedTask(ip) != null){
				//if the task is failed over the ignore time then stop to try it
				if( (new Date()).getTime() - getFailedTask(ip) >  IGNORE_TIME_MILLISECOND){
					removeFromFailedTasks(ip);
					return;
				}
			}else{
				addToFailedTasks(ip, (new Date()).getTime());
			}
	        GetIPInfoTask getIPInfoTask = new GetIPInfoTask(new GetIPInfoCallable(mac, ip));	  
	        FarmServer.getExecutors().submit(getIPInfoTask);
		}else{
			removeFromFailedTasks(ip);
		}
	}

	public void addToFailedTasks(String ip, Long date){
		failedTasks.put(ip, date);
    }
    
    public void removeFromFailedTasks(String ip){
    	failedTasks.remove(ip);
    }
    
    public Long getFailedTask(String ip){
        return failedTasks.get(ip);
    }
	
}
